package com.itlong.cloud.intercept.sdkV1;

import com.itlong.cloud.POJO.PO.PropertyUserInfoPO;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.noncore.commons.IOperationLogServiceClient;
import com.itlong.cloud.user.sdk.ISDKServerOldUserServiceClient;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.encrypt.DesEncryptUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.random.LogicIdUtil;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <desc>
 *      SDK开发者日志记录器
 * </desc>
 *
 * @createDate 2018/12/19
 */
@Aspect
@Component
public class DeveloperLogInterceptor {

    // 定义一个切入点
    @Pointcut("execution(* com.itlong.cloud.controller.sdkV1.cloud..*.*(..))")
    public void excudeService(){}

    @Autowired
    IOperationLogServiceClient iOperationLogServiceClient;

    @Autowired
    ISDKServerOldUserServiceClient iSDKUserServiceClient;

    /**
     * <desc>
     *      开发者访问日志拦截器
     * </desc>
     *
     * @param thisJoinPoint
     * @author wangzhi
     * @createDate 2018/12/19
     */
    @Around("excudeService() && @annotation(loggerInfo)")
    public Object twiceAsOld(ProceedingJoinPoint thisJoinPoint, LoggerInfo loggerInfo) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String appId=request.getParameter("appId");
        String ip = HttpProtocolUtil.getIpAddr(request);
        PropertyUserInfoPO propertyUserInfoPO = iSDKUserServiceClient.getPropertyUserByAppId(appId);
        Map<String,Object> map = new HashMap<>();
        Object result = null;

        // 正常保存访问日志（请求参数有加密）
        if (propertyUserInfoPO != null) {
            map.put("logId", LogicIdUtil.bussinessId());
            map.put("account",propertyUserInfoPO.getUserName());

            String encryptScript = request.getParameter("encryptScript");
            if (StringUtils.isBlank(encryptScript)) {
                return thisJoinPoint.proceed();
            }
            //验证MD5是否正确
//            String content=StringHandlerUtil.replaceBlank(encryptScript.substring(0, encryptScript.length() - 32));
//            String md5=encryptScript.substring(encryptScript.length() - 32, encryptScript.length());
//            if(!Md5EncryptUtil.md5(content + propertyUserInfoPO.getAppsecret()).toUpperCase().equals(md5)){
//                return thisJoinPoint.proceed();
//            }
            String encryptResult = DesEncryptUtil.aesDecrypt(encryptScript, propertyUserInfoPO.getAppsecret());
            Map<String,Object> params = JsonUtil.toObject(encryptResult,HashMap.class);

//            if (params.get("projectId") != null) {
//                map.put("projectId",DesEncryptUtil.projectIdDesEncrypt(params.get("projectId").toString()) == null ? params.get("projectId") : DesEncryptUtil.projectIdDesEncrypt(params.get("projectId").toString()));
//            }
            map.put("projectId",params.get("projectId"));
            if (request.getAttribute("portType") == null || request.getAttribute("remark") == null) {
                result = thisJoinPoint.proceed();
            }
            map.put("portType",request.getAttribute("portType"));// 接口类别
            map.put("developerUse",loggerInfo.operateDesc());
            map.put("remark",request.getAttribute("remark"));// 详细描述
            map.put("ip",ip);
            //消费消息时再查询 map.put("ipAddress", HttpProtocolUtil.getIpAddressFromBaidu(ip));
            map.put("ipAddress", "");
            map.put("status", DataStatusEnum.NORMAL.getType());
            Date nowTime = new Date();
            String timeStr = new SimpleDateFormat(DateUtil.DATE_FORMAT_TYPE1).format(nowTime);
            map.put("createTime",timeStr);
            map.put("updateTime",timeStr);
            iOperationLogServiceClient.saveDeveloperLog(map);
        }

        // 不加密参数记录日志
//        if (propertyUserInfoPO != null) {
//            map.put("logId",LogicIdUtil.bussinessId());
//            map.put("account",propertyUserInfoPO.getUserName());
//
////            if (request.getParameter("projectId") != null) {
////                map.put("projectId",DesEncryptUtil.projectIdDesEncrypt(request.getParameter("projectId")) == null ? request.getParameter("projectId") : DesEncryptUtil.projectIdDesEncrypt(request.getParameter("projectId")));
////            }
//            map.put("projectId",request.getParameter("projectId"));
//            if (request.getAttribute("portType") == null || request.getAttribute("remark") == null) {
//                result = thisJoinPoint.proceed();
//            }
//            map.put("portType",request.getAttribute("portType"));// 接口类别
//            map.put("developerUse",loggerInfo.operateDesc());
//            map.put("remark",request.getAttribute("remark"));// 详细描述
//            map.put("ip",ip);
//            map.put("ipAddress",HttpProtocolUtil.getIpAddressFromBaidu(ip));
//            map.put("status",DataStatusEnum.NORMAL.getType());
//            Date nowTime = new Date();
//            String timeStr = new SimpleDateFormat(DateUtil.DATE_FORMAT_TYPE1).format(nowTime);
//            map.put("createTime",timeStr);
//            map.put("updateTime",timeStr);
//            iOperationLogServiceClient.saveDeveloperLog(map);
//        }

        return result;

    }

}
